﻿#region << 版 本 注 释 >>

/*----------------------------------------------------------------
 * 版权所有 (c) 2022 HP Inc.  保留所有权利。
 * CLR版本：4.0.30319.42000
 * 机器名称：朱宇辉
 * 唯一标识：916ae88f-4a68-4960-ab1b-8f1c616a8a53
 * 文件名：ApiResponseHandler
 * 当前用户域：朱宇辉
 * 
 * 创建者：朱宇辉
 * 电子邮箱：17608422149@163.com
 * 创建时间：2022/7/27 14:10:53
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

#endregion << 版 本 注 释 >>

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Service.Framework.Packet;
using Service.Framework.Utils;
using System.Text.Encodings.Web;

namespace Service.Core.Identity.Handler
{
    /// <summary>
    /// 
    /// </summary>
    public class ApiResponseHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        private readonly JsonSerializerSettings _jsonSerializerSettings;

        public ApiResponseHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        {

            _jsonSerializerSettings = new JsonSerializerSettings()
            {
                ContractResolver = new CustomContractResolver(),
                DateFormatString = "yyyy-MM-dd HH:mm:ss",
            };
            //jsonSerializerSettings.Converters.Add(new StringEnumConverter());
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="properties"></param>
        protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.ContentType = "application/json";
            Response.StatusCode = StatusCodes.Status401Unauthorized;
            await Response.WriteAsync(JsonConvert.SerializeObject(R.ErrorMessage("很抱歉，您无权访问该接口，请确保已经登录!"), _jsonSerializerSettings));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="properties"></param>
        protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
        {
            Response.ContentType = "application/json";
            Response.StatusCode = StatusCodes.Status403Forbidden;
            await Response.WriteAsync(JsonConvert.SerializeObject(R.ErrorMessage("很抱歉，您的访问权限等级不够，联系管理员!"), _jsonSerializerSettings));
        }
    }
}